import React, { useState, useEffect } from 'react';
import { Table, Button, Form, Select, DatePicker, Input, Row, Col, Tabs, Modal, Pagination, Tag, Radio, Checkbox, message, Switch } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import {
  getAnomalyDetectionList,
  getAnomalyResultById,
  addAnomalyDetectionTask,
  downloadAnomalyResult,
  type AnomalyDetectionItem,
  type AnomalyResultItem,
  type AnomalyDetectionQueryParams
} from '../api/anomalyDetection';
import { useMockData, developmentConfig, devLog } from '../config/development';
import Breadcrumb from '../components/Breadcrumb';
import './AnomalyDetection.css';

// 异常详情数据类型定义
interface AnomalyDetailData extends AnomalyResultItem {
  key: string;
}

// 模拟数据定义
const mockAnomalyData: AnomalyDetectionItem[] = [
  {
    id: 'Sjctjc0005',
    checkType: '自定义检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0004',
    checkType: '增量检测',
    checkRange: '--',
    checkTime: '2021-08-23 11:50:21',
    status: '异常',
    anomalyReason: '重复文件11个，0字节文件1个，0字节...'
  },
  {
    id: 'Sjctjc0005',
    checkType: '全量检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0004',
    checkType: '增量检测',
    checkRange: '--',
    checkTime: '2021-08-23 11:50:21',
    status: '异常',
    anomalyReason: '重复文件11个，0字节文件1个，0字节...'
  },
  {
    id: 'Sjctjc0005',
    checkType: '自定义检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '全量检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '自定义检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '全量检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '自定义检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '全量检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '自定义检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
  {
    id: 'Sjctjc0005',
    checkType: '全量检测',
    checkRange: 'TW1全部\\全部 20240911000000--20240911240000',
    checkTime: '2021-08-23 11:50:21',
    status: '正常',
  },
];

// 模拟异常详情数据
const mockAnomalyDetailData: AnomalyDetailData[] = [
  {
    key: '1',
    sequenceNo: 1,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 3,
    actualFileCount: 5,
    anomalyReason: '重复文件',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '2',
    sequenceNo: 2,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '0',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '0字节文件',
    storageLocation: '磁盘',
    operation: '编辑'
  },
  {
    key: '3',
    sequenceNo: 3,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '4',
    sequenceNo: 4,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.5',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '5',
    sequenceNo: 5,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 3,
    actualFileCount: 5,
    anomalyReason: '重复文件',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '6',
    sequenceNo: 6,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '0',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '0字节文件',
    storageLocation: '磁盘',
    operation: '编辑'
  },
  {
    key: '7',
    sequenceNo: 7,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '8',
    sequenceNo: 8,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.5',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '9',
    sequenceNo: 9,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 3,
    actualFileCount: 5,
    anomalyReason: '重复文件',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '10',
    sequenceNo: 10,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '0',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '0字节文件',
    storageLocation: '磁盘',
    operation: '编辑'
  },
  {
    key: '11',
    sequenceNo: 11,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '12',
    sequenceNo: 12,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.5',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '13',
    sequenceNo: 13,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 3,
    actualFileCount: 5,
    anomalyReason: '重复文件',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '14',
    sequenceNo: 14,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '0',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '0字节文件',
    storageLocation: '磁盘',
    operation: '编辑'
  },
  {
    key: '15',
    sequenceNo: 15,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.3',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
  {
    key: '16',
    sequenceNo: 16,
    fileName: 'TW1-Spectra-DataSet-20230101',
    filePath: '/archive/2024/03/file2.csv1.2',
    fileSize: '2.5',
    fileCount: 2,
    actualFileCount: 2,
    anomalyReason: '--',
    storageLocation: '数据库',
    operation: '编辑'
  },
];

const AnomalyDetection: React.FC = () => {
  const [form] = Form.useForm();
  const [detectionForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState('all');
  const [detailActiveTab, setDetailActiveTab] = useState('all');
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<AnomalyDetectionItem | null>(null);
  const [loading, setLoading] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  
  // 数据状态
  const [anomalyData, setAnomalyData] = useState<AnomalyDetectionItem[]>([]);
  const [anomalyDetailData, setAnomalyDetailData] = useState<AnomalyDetailData[]>([]);
  const [total, setTotal] = useState(0);
  const [detailTotal, setDetailTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [detailCurrentPage, setDetailCurrentPage] = useState(1);
  const [detailPageSize, setDetailPageSize] = useState(20);
  const [detailReasonFilter, setDetailReasonFilter] = useState<string[]>([]);

  // 统计数据
  const [allCount, setAllCount] = useState(0);
  const [abnormalCount, setAbnormalCount] = useState(0);
  const [normalCount, setNormalCount] = useState(0);

  // 获取模拟数据开关状态
  const USE_MOCK_DATA = useMockData.anomalyDetection();

  // 获取异常检测列表数据
  const fetchAnomalyData = async (params?: Partial<AnomalyDetectionQueryParams>) => {
    if (USE_MOCK_DATA) {
      // 使用模拟数据
      devLog('使用模拟数据加载异常检测列表', { params, activeTab });
      setLoading(true);
      setTimeout(() => {
        let filteredData = [...mockAnomalyData];
        
        // 根据当前标签页过滤状态
        if (activeTab === 'abnormal') {
          filteredData = filteredData.filter(item => item.status === '异常');
        } else if (activeTab === 'normal') {
          filteredData = filteredData.filter(item => item.status === '正常');
        }
        
        // 分页处理
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedData = filteredData.slice(startIndex, endIndex);
        
        setAnomalyData(paginatedData);
        setTotal(filteredData.length);
        
        // 更新统计数据
        const abnormal = mockAnomalyData.filter(item => item.status === '异常').length;
        const normal = mockAnomalyData.filter(item => item.status === '正常').length;
        setAllCount(mockAnomalyData.length);
        setAbnormalCount(abnormal);
        setNormalCount(normal);
        
        setLoading(false);
      }, developmentConfig.api.mockDelay); // 使用配置的模拟延迟
      return;
    }

    // 使用真实API
    devLog('使用真实API加载异常检测列表', { params, activeTab });
    setLoading(true);
    try {
      const queryParams: AnomalyDetectionQueryParams = {
        page: currentPage,
        ps: pageSize,
        ...params
      };

      // 根据当前标签页过滤状态
      if (activeTab === 'abnormal') {
        (queryParams as any).is_abnormal = '1';
      } else if (activeTab === 'normal') {
        (queryParams as any).is_abnormal = '0';
      }

      const response = await getAnomalyDetectionList(queryParams);
      
      if (response.code === 200 || response.code === 0) {
        // 适配后端数据结构
        const adaptedData = (response.data || []).map((item: any, idx: number) => ({
          ...item,
          key: idx,
          is_abnormal: item.is_abnormal ?? '',
        }));
        setAnomalyData(adaptedData);
        setTotal(response.total || 0);
      } else {
        message.error('获取数据失败');
      }
    } catch (error) {
      console.error('获取异常检测数据失败:', error);
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取异常详情数据
  const fetchAnomalyDetail = async (id: string, page = 1, ps = 10, reason?: string) => {
    if (USE_MOCK_DATA) {
      // 使用模拟数据
      devLog('使用模拟数据加载异常详情', { id, page, ps, reason });
      setDetailLoading(true);
      setTimeout(() => {
        // 分页处理
        const startIndex = (page - 1) * ps;
        const endIndex = startIndex + ps;
        const paginatedData = mockAnomalyDetailData.slice(startIndex, endIndex);

        setAnomalyDetailData(paginatedData);
        setDetailTotal(mockAnomalyDetailData.length);
        setDetailLoading(false);
      }, developmentConfig.api.mockDelay / 2); // 详情加载稍快一些
      return;
    }

    // 使用真实API
    devLog('使用真实API加载异常详情', { id, page, ps, reason });
    setDetailLoading(true);
    try {
      const response = await getAnomalyResultById({
        id,
        page,
        ps,
        reason
      });

      if (response.code === 200 || response.code === 0) {
        const detailData = response.data?.map((item: any, index: number) => ({
          ...item,
          key: `${id}_${index}`,
          sequenceNo: (page - 1) * ps + index + 1
        })) || [];

        setAnomalyDetailData(detailData);
        setDetailTotal(response.total || 0);
      } else {
        message.error('获取详情数据失败');
      }
    } catch (error) {
      console.error('获取异常详情数据失败:', error);
      message.error('获取详情数据失败');
    } finally {
      setDetailLoading(false);
    }
  };

  // 获取统计数据（全部/异常/正常数量）
  const fetchStatistics = async () => {
    if (USE_MOCK_DATA) {
      // 模拟数据统计 - 这部分已经是正确的，直接使用完整数据源
      const abnormal = mockAnomalyData.filter(item => item.status === '异常').length;
      const normal = mockAnomalyData.filter(item => item.status === '正常').length;
      setAllCount(mockAnomalyData.length);
      setAbnormalCount(abnormal);
      setNormalCount(normal);
      return;
    }

    // 使用真实API获取统计
    try {
      // 并行请求获取异常和正常的总数
      const [abnormalResponse, normalResponse] = await Promise.all([
        getAnomalyDetectionList({ page: 1, ps: 1, is_abnormal: '1' } as any),
        getAnomalyDetectionList({ page: 1, ps: 1, is_abnormal: '0' } as any)
      ]);

      const abnormalTotal = (abnormalResponse.code === 200 || abnormalResponse.code === 0)
        ? (abnormalResponse.total || 0)
        : 0;
      const normalTotal = (normalResponse.code === 200 || normalResponse.code === 0)
        ? (normalResponse.total || 0)
        : 0;

      setAbnormalCount(abnormalTotal);
      setNormalCount(normalTotal);
      setAllCount(abnormalTotal + normalTotal);
    } catch (error) {
      console.error('获取统计数据失败:', error);
      // 失败时不修改统计数据，保持现有值
    }
  };

  // 页面初始化时加载数据
  useEffect(() => {
    fetchAnomalyData();
    fetchStatistics(); // 同时获取统计数据
  }, [currentPage, pageSize, activeTab]);

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (_, __, index) => (currentPage - 1) * pageSize + index + 1,
    },
    {
      title: '用户账号',
      dataIndex: 'user',
      key: 'user',
      width: 120,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '内容',
      dataIndex: 'task',
      key: 'task',
      width: 120,
    },
    {
      title: '检测时间',
      dataIndex: 'ctime',
      key: 'ctime',
      width: 160,
    },
    {
      title: '更新时间',
      dataIndex: 'utime',
      key: 'utime',
      width: 160,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        let text = '';
        let color = '';
        switch (status) {
          case '1':
            text = '正在检测';
            color = 'blue';
            break;
          case '2':
            text = '完成';
            color = 'green';
            break;
          case '0':
            text = '错误退出';
            color = 'red';
            break;
          default:
            text = status;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '是否异常',
      dataIndex: 'is_abnormal',
      key: 'is_abnormal',
      width: 100,
      render: (is_abnormal) => (
        <Tag color={is_abnormal === '1' ? 'red' : 'green'}>
          {is_abnormal === '1' ? '存在异常' : '无异常'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      width: 100,
      render: (_, record) => (
        <Button 
          type="link" 
          onClick={() => {
            setCurrentRecord(record);
            setDetailVisible(true);
            setDetailCurrentPage(1);
            fetchAnomalyDetail((record.id || '').toString(), 1, detailPageSize);
          }}
        >
          详情
        </Button>
      ),
    },
  ];

  // 详情表格列定义
  const detailColumns: ColumnsType<any> = [
    {
      title: '序号',
      dataIndex: 'sequenceNo',
      key: 'sequenceNo',
      width: 60,
    },
    {
      title: '文件名',
      dataIndex: 'file',
      key: 'file',
      width: 400,
    },
    {
      title: '异常类型',
      dataIndex: 'errType',
      key: 'errType',
      width: 120,
      render: (errType) => {
        let text = '';
        let color = '';
        switch (errType) {
          case 'fileSys':
            text = '文件异常';
            color = 'red';
            break;
          case 'dataBase':
            text = '数据库异常';
            color = 'orange';
            break;
          default:
            text = errType;
            color = 'default';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '异常原因',
      dataIndex: 'reason',
      key: 'reason',
      width: 400,
    },
    {
      title: '创建时间',
      dataIndex: 'ctime',
      key: 'ctime',
      width: 160,
    },
    {
      title: '处理时间',
      dataIndex: 'utime',
      key: 'utime',
      width: 160,
    },
  ];

  // 异常检测类型标签页
  const tabs = [
    { key: 'all', label: `全部(${allCount})`, count: allCount },
    { key: 'abnormal', label: `异常(${abnormalCount})`, count: abnormalCount },
    { key: 'normal', label: `正常(${normalCount})`, count: normalCount },
  ];

  // 表单提交处理
  const onFinish = (values: any) => {
    console.log('筛选条件:', values);
    
    if (USE_MOCK_DATA) {
      // 模拟数据筛选逻辑
      message.info('模拟数据模式：筛选功能演示');
      return;
    }
    
    // 构建查询参数
    const queryParams: Partial<AnomalyDetectionQueryParams> = {};
    
    if (values.id) {
      queryParams.id = values.id;
    }
    
    if (values.status) {
      queryParams.status = values.status === 'normal' ? '正常' : '异常';
    }
    
    if (values.checkTime) {
      queryParams.checkTime = dayjs(values.checkTime).format('YYYY-MM-DD HH:mm:ss');
    }
    
    // 重置到第一页并查询
    setCurrentPage(1);
    fetchAnomalyData(queryParams);
  };

  // 清除筛选条件
  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    fetchAnomalyData();
  };

  // 处理任务类型选择（多选，允许多选，不再有"全部类型"逻辑）
  const handleTaskTypeChange = (checkedValues: string[]) => {
    detectionForm.setFieldsValue({ taskTypes: checkedValues });
  };

  // 处理检测任务执行
  const handleDetectionSubmit = async () => {
    if (USE_MOCK_DATA) {
      message.success('模拟数据模式：异常检测任务添加成功');
      fetchAnomalyData();
      return;
    }
    try {
      const values = await detectionForm.validateFields();
      const selectedTasks = values.taskTypes || [];
      const taskString = selectedTasks.join(',');
      const response = await addAnomalyDetectionTask({ task: taskString });
      if (response.code === 200 || response.code === 0) {
        message.success('异常检测任务添加成功');
        fetchStatistics(); // 先更新统计数据
        fetchAnomalyData(); // 再更新列表数据
      } else {
        message.error(response.message || '添加异常检测任务失败');
      }
    } catch (error) {
      console.log('表单验证失败:', error);
    }
  };

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  // 处理分页变化
  const handlePageChange = (page: number, size?: number) => {
    setCurrentPage(page);
    if (size && size !== pageSize) {
      setPageSize(size);
    }
  };

  // 处理详情分页变化
  const handleDetailPageChange = (page: number, size?: number) => {
    setDetailCurrentPage(page);
    if (size && size !== detailPageSize) {
      setDetailPageSize(size);
    }

    if (currentRecord) {
      const reasonStr = detailReasonFilter.length > 0 ? detailReasonFilter.join(';') : undefined;
      fetchAnomalyDetail((currentRecord.id || '').toString(), page, size || detailPageSize, reasonStr);
    }
  };

  // 处理异常原因筛选
  const handleDetailFilter = () => {
    if (!currentRecord) return;
    setDetailCurrentPage(1);
    const reasonStr = detailReasonFilter.length > 0 ? detailReasonFilter.join(';') : undefined;
    fetchAnomalyDetail((currentRecord.id || '').toString(), 1, detailPageSize, reasonStr);
  };

  // 处理导出
  const handleExport = async () => {
    if (!currentRecord) return;
    try {
      const reasonStr = detailReasonFilter.length > 0 ? detailReasonFilter.join(';') : undefined;
      await downloadAnomalyResult({
        id: (currentRecord.id || '').toString(),
        reason: reasonStr
      });
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  return (
    <div className="anomaly-detection-container">
      <div className="page-header">
        <Breadcrumb text="数据管理 > 数据异常检测" style={{ marginBottom: 0 }} />
        {/* 开发模式指示器 */}
        {USE_MOCK_DATA && developmentConfig.ui.showMockDataIndicator && (
          <div style={{ 
            position: 'absolute', 
            top: '10px', 
            right: '20px', 
            background: '#ff4d4f', 
            color: 'white', 
            padding: '4px 8px', 
            borderRadius: '4px', 
            fontSize: '12px',
            fontWeight: 'bold'
          }}>
            模拟数据模式
          </div>
        )}
      </div>
      
      {/* 数据异常检测表单，放在filter-section上方 */}
      <div className="anomaly-detection-inline-form" style={{ marginBottom: 16, background: '#fff', padding: 16, borderRadius: 4, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <Form
          form={detectionForm}
          layout="inline"
          initialValues={{ taskTypes: [] }}
        >
          <Form.Item
            label="任务类型："
            name="taskTypes"
            rules={[{ required: true, message: '请选择任务类型' }]}
          >
            <Checkbox.Group onChange={handleTaskTypeChange} className="task-types-checkbox">
              <Checkbox value="TW2">TW2</Checkbox>
              <Checkbox value="TW1">TW1</Checkbox>
              <Checkbox value="CE1">CE1</Checkbox>
              <Checkbox value="CE2">CE2</Checkbox>
              <Checkbox value="CE3">CE3</Checkbox>
              <Checkbox value="CE4">CE4</Checkbox>
              <Checkbox value="CE5">CE5</Checkbox>
              <Checkbox value="CE6">CE6</Checkbox>
            </Checkbox.Group>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleDetectionSubmit}>执行</Button>
          </Form.Item>
        </Form>
      </div>

      
      
      <div className="tabs-section">
        {tabs.map(tab => (
          <span
            key={tab.key}
            className={`tab-item ${activeTab === tab.key ? 'active' : ''}`}
            onClick={() => handleTabChange(tab.key)}
          >
            {tab.label}
          </span>
        ))}
      </div>
      
      <Table
        columns={columns}
        dataSource={anomalyData}
        loading={loading}
        bordered
        pagination={false}
        rowKey="id"
        rowClassName={(record, index) => {
          let base = '';
          if (record.status === '异常') base = 'highlight-row ';
          return base + (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even');
        }}
        scroll={{ x: 1200 }}
        style={{ marginBottom: 16 }}
      />
      
      <div className="pagination-container">
        <Pagination
          total={total}
          current={currentPage}
          pageSize={pageSize}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={handlePageChange}
        />
      </div>
      
      <Modal
        title={<div>异常详情 <span className="modal-subtitle">ID: {currentRecord?.id}</span></div>}
        open={detailVisible}
        onCancel={() => {
          setDetailVisible(false);
          setDetailReasonFilter([]);
        }}
        width={1600}
        footer={null}
        className="anomaly-detail-modal"
      >
        <div style={{ marginBottom: 16, display: 'flex', gap: 8, alignItems: 'center' }}>
          <span>异常原因：</span>
          <Select
            mode="multiple"
            placeholder="请选择异常原因"
            value={detailReasonFilter}
            onChange={setDetailReasonFilter}
            style={{ flex: 1, minWidth: 400 }}
            options={[
              { label: '0字节文件', value: '0字节文件' },
              { label: '文件重复', value: '文件重复' },
              { label: '数据库记录缺失', value: '数据库记录缺失' },
              { label: '重复记录', value: '重复记录' },
              { label: '0字节记录', value: '0字节记录' },
              { label: '完备性校验', value: '完备性校验' },
              { label: '非空字段', value: '非空字段' },
              { label: '文件缺失', value: '文件缺失' },
            ]}
          />
          <Button type="primary" onClick={handleDetailFilter}>
            筛选
          </Button>
          <Button onClick={handleExport}>
            导出
          </Button>
        </div>
        <Table
          columns={detailColumns}
          dataSource={anomalyDetailData}
          loading={detailLoading}
          pagination={{
            total: detailTotal,
            current: detailCurrentPage,
            pageSize: detailPageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: handleDetailPageChange,
          }}
          bordered
          size="small"
          rowKey="key"
          scroll={{ x: 1400, y: 400 }}
          rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          className="anomaly-detail-table-wrap"
        />
        <div className="detail-footer">
          <div className="total-info">共{detailTotal}条数据</div>
        </div>
      </Modal>
    </div>
  );
};

export default AnomalyDetection; 